﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;

namespace LiuYan.Interface
{
    public class Common
    {
        /// <summary>
        /// 微信签名算法
        /// </summary>
        /// <param name="dic"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetSign(Dictionary<string, string> dic, string key)
        {
            var str = "";
            var dicSort = from objDic in dic orderby objDic.Key select objDic;// 按ASICII排序
            foreach (KeyValuePair<string, string> kvp in dicSort)
            {
                str += kvp.Key + "=" + kvp.Value + "&";
            }
            str += "key=" + key;// 商户key
            return FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToUpper();
        }
        /// <summary>
        /// 生成xml
        /// </summary>
        /// <param name="sParams">字典</param>
        public string CreateXML(Dictionary<string, string> sParams)
        {
                StringBuilder sbPay = new StringBuilder();
                foreach (KeyValuePair<string, string> k in sParams)// 组装xml数据
                {
                    sbPay.Append("<" + k.Key + "><![CDATA[" + k.Value + "]]></" + k.Key + ">");
                }
                return String.Format("<xml>{0}</xml>", sbPay);
        }

        /// <summary>
        ///  时间戳
        /// </summary>
        /// <returns></returns>
        public  string GenerateTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }

        /// <summary>
        /// 生成随机串，随机串包含字母或数字
        /// </summary>
        /// <returns></returns>
        public  string GenerateNonceStr()
        {
            return Guid.NewGuid().ToString().Replace("-", "");
        }
    }
}